package com.alex.server.service.impl;

import com.alex.server.domain.Section;
import com.alex.server.domain.SectionExample;
import com.alex.server.dto.SectionDto;
import com.alex.server.dto.PageDto;
import com.alex.server.dto.SectionPageDto;
import com.alex.server.enums.SectionChargeEnum;
import com.alex.server.mapper.SectionMapper;
import com.alex.server.service.ICourseService;
import com.alex.server.service.ISectionService;
import com.alex.server.util.CopyUtil;
import com.alex.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class SectionServiceImpl implements ISectionService {

    @Autowired
    private SectionMapper mapper;

    @Autowired
    private ICourseService courseService;

    @Override
    public PageDto list(SectionPageDto sectionPageDto) {
        PageHelper.startPage(sectionPageDto.getPage(),sectionPageDto.getSize());
        SectionExample sectionExample = new SectionExample();
        SectionExample.Criteria criteria = sectionExample.createCriteria();
        if (!StringUtils.isEmpty(sectionPageDto.getCourseId())) {
            criteria.andCourseIdEqualTo(sectionPageDto.getCourseId());
        }
        if (!StringUtils.isEmpty(sectionPageDto.getChapterId())) {
            criteria.andChapterIdEqualTo(sectionPageDto.getChapterId());
        }
        sectionExample.setOrderByClause("sort asc");
        List<Section> sectionList = mapper.selectByExample(sectionExample);
        PageInfo<Section> pageInfo = new PageInfo<>(sectionList);
        sectionPageDto.setTotal(pageInfo.getTotal());
        List<SectionDto> sectionDtoList = CopyUtil.copyList(sectionList, SectionDto.class);
        sectionPageDto.setList(sectionDtoList);
        return sectionPageDto;
    }

    @Override
    @Transactional
    public void save(SectionDto sectionDto) {
        Section section = CopyUtil.copy(sectionDto, Section.class);
        if (StringUtils.isEmpty(sectionDto.getId())){
            this.insert(section);
        } else {
            this.update(section);
        }
        courseService.updateTime(sectionDto.getCourseId());
    }

    @Override
    public void insert(Section section) {
        Date now = new Date();
        section.setCreateTime(now);
        section.setUpdateTime(now);
        section.setId(UuidUtil.getShortUuid());
        section.setCharge(SectionChargeEnum.CHARGE.getCode());
        mapper.insert(section);
    }

    @Override
    public void update(Section section) {
        mapper.updateByPrimaryKey(section);
    }

    @Override
    public void delete(String id) {
        mapper.deleteByPrimaryKey(id);
    }

}